/**
 * 处理所有以/addcart开头请求的路由器
 */
const express = require("express");
const pool = require("../pool");
let router = express.Router();
module.exports = router;
// 添加商品路由
router.post("/addcart", (req, res, next) => {
  let pid = req.body.pid;
  let uid = req.body.uid;
  // console.log(pid,uid);
  let sql = `SELECT * FROM shoppingcart WHERE uid=? AND pid=?`;
  //根据uid和pid查找shoppingcart 是否存在重复的uid和 pid的对应关系
  pool.query(sql, [uid,pid], (err, result) => {
    if (err) {
      next(err);
      return
    }
     //如果存在让num+1 并且更新数据库num值返回num和code值
    //  console.log(result);
    if (result.length > 0) {
      let num = result[0].num + 1;
      let sql = "UPDATE shoppingcart set num=? WHERE uid=? AND pid=?";
      pool.query(sql, [num,uid,pid], (err, result) => {
        if (err) {
          next(err);
          return;
        }
        let output = {
          num: num,
          code: 200
        };
        console.log(output);
        res.json(output);
      });
    } else {  
      //否则不存在执行插入操作(默认插入num值为1)  返回num和code值
      let num = 1;
      let sql = " INSERT INTO shoppingCart (uid,pid,num) VALUES (?,?,?)" ;
      pool.query(sql, [uid, pid, num], (err, result) => {
        if (err) {
          next(err);
          return;
        }
        let output = {
          num: num,
          code: 200
        };
        console.log(output);
        res.json(output);
      });
    }   
  });
});
//根据uid查询用户购物车信息 返回{pid:xxx,num:xxx}的数组
router.get('/getcart', (req, res, next) => { 
  let uid = req.query.uid
  let sql = "SELECT pid,num FROM shoppingcart WHERE uid=?";
  pool.query(sql, uid, (err, result) => { 
    if (err) {
      next(err);
      return;
    }
    // console.log(result);
    res.json(result)
  })
})
//根据uid和pid更新购物车表信息
router.post('/updatenum', (req, res, next) => { 
  let pid = req.body.pid
  let num = req.body.num
  let sql = "UPDATE shoppingcart set num=? WHERE pid=?";
  pool.query(sql, [num,pid], (err, result) => { 
    if (err) {
      next(err);
      return;
    }
    if (result.affectedRows > 0) { 
      let output = {
        num:num,
        code: 200,
        msg:"num 更新成功"
      }
    res.json(output)
    }     
  })
})